# !usr/bin/env python
# -*- coding:utf-8 -*-
import sys
from PyQt5 import QtWidgets
from mainwindow import Ui_MainWindow
from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox

uart_name_list= list()
count = int(0)
uart_desc_list = list()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
	def __init__(self, parent = None):
		super(MainWindow, self).__init__(parent)
		self.setupUi(self)
		self.uart_init()
		self.setSignalSlot()

	'''生成串口和其厂家信息，并将串口信息中的名称和厂家信息添加进列表，在combobox中添加'''
	def uart_init(self):
		global uart_name_list, uart_desc_list, count
		self.plainTextEdit.setReadOnly(1)
		self.com = QSerialPort()
		port_numb = QSerialPortInfo.availablePorts()
		for info in port_numb:
			if info.portName().count('COM', 0, len(info.portName())) != 0:
				uart_str_desc = info.description().split()
				# print("uart_str_desc= %s" % uart_str_desc)
				uart_str_name = info.portName().split()
				uart_name_list.append(uart_str_name[0])
				uart_desc_list.append(uart_str_desc[0])
				# print("uart_desc_list= %s" % uart_desc_list)

		else:
			# print("uart_desc_list = %s" % uart_desc_list)
			# print("uart_name_list = %s" % uart_name_list)
			count = str(uart_name_list).count('COM', 0, len(str(uart_name_list)))
			# print("count= %s" % count)
			if count > 256:
				QMessageBox.critical(self, '错误', '连接串口太多')
			else:
				self.cmb_port_name.clear()
				for i in range(0, count):
					self.cmb_port_name.addItem(uart_name_list[i] + ' ' + uart_desc_list[i])

	def setSignalSlot(self):
		self.btn_open.clicked.connect(self.btn_open_port)
		self.btn_close.clicked.connect(self.btn_close_port)
		self.btn_send.clicked.connect(self.btn_send_data)
		self.com.readyRead.connect(self.receive_data)
		self.btn_clear.clicked.connect(self.btn_clear_receive)

	'''对比列表与combobox中的信息，如果匹配就打开'''
	def btn_open_port(self):
		global uart_desc_list, uart_name_list, count
		for i in range(0, count):
			if (uart_name_list[i] + ' ' + uart_desc_list[i]) == self.cmb_port_name.currentText():
				self.com.setPortName(uart_name_list[i])
		if self.cmb_port_rate.currentText() == "115200":
			self.com.setBaudRate(QSerialPort.Baud115200)
		elif self.cmb_port_rate.currentText() == "38400":
			self.com.setBaudRate(QSerialPort.Baud38400)
		elif self.cmb_port_rate.currentText() == "19200":
			self.com.setBaudRate(QSerialPort.Baud19200)
		elif self.cmb_port_rate.currentText() == "9600":
			self.com.setBaudRate(QSerialPort.Baud9600)
		elif self.cmb_port_rate.currentText() == "4800":
			self.com.setBaudRate(QSerialPort.Baud4800)
		elif self.cmb_port_rate.currentText() == "2400":
			self.com.setBaudRate(QSerialPort.Baud2400)
		else:
			pass

		if self.cmb_data_num.currentText() == "8":
			self.com.setDataBits(QSerialPort.Data8)
		elif self.cmb_data_num.currentText() == "7":
			self.com.setDataBits(QSerialPort.Data7)
		else:
			pass

		if self.cmb_stop_num.currentText() == "1":
			self.com.setStopBits(QSerialPort.OneStop)
		elif self.cmb_stop_num.currentText() == "1.5":
			self.com.setStopBits(QSerialPort.OneAndHalfStop)
		else:
			pass

		if self.cmb_pority.currentText() == "Odd":
			self.com.setParity(QSerialPort.OddParity)
		elif self.cmb_pority.currentText() == "Even":
			self.com.setParity(QSerialPort.EvenParity)
		else:
			self.com.setParity(QSerialPort.NoParity)

		self.com.open(QSerialPort.ReadWrite)
		if self.com.isOpen():
			self.lab_status.setText("Connected")
		else:
			QMessageBox.critical(self, '错误', '串口打开失败')

	def btn_close_port(self):
		self.com.close()
		self.lab_status.setText("Disconnected")

	def btn_send_data(self):
		tx_data = self.lint_send_data.text()
		self.com.write(tx_data.encode())

	def receive_data(self):
		rx_data = bytes(self.com.readAll())
		if self.checkBox.checkState() == Qt.Checked:
			rx_strtohex = str(rx_data)
			self.plainTextEdit.insertPlainText(self.str_to_hex(rx_strtohex) + '\n')
		else:
			self.plainTextEdit.insertPlainText(rx_data.decode())
			# 当接收字符超出页面时，自动滚屏
            self.plainTextEdit.ensureCursorVisible()
            self.setFocus()

	def btn_clear_receive(self):
		self.plainTextEdit.clear()

	def str_to_hex(self, s):
		return ' '.join([hex(ord(c)).replace('0x', '') for c in s])

	# def hex_to_str(self, s):
	# 	return ''.join([chr(i) for i in [int(b, 16) for b in s.split(' ')]])

if __name__ == "__main__":
	app = QtWidgets.QApplication(sys.argv)
	uart_gui = MainWindow()
	uart_gui.show()
	sys.exit(app.exec_())